<?php
/**
 * 前台总控制器
 * @author cjli
 *
 */
class HomeAction extends Action
{
		/**
		 * 初始化
		 */
    public function _initialize()
    {
            //获取传参的类
		    import('@.ORG.Request');
		    $this->Request = new Request();

    	    //保存配置值
			$configList = SiteModel::get_shop_config_list();
			C($configList);

			header("Content-Type:text/html; charset=".C('DEFAULT_CHARSET'));
			defined('THEMES_PATH') or define('THEMES_PATH', TMPL_PATH.C('DEFAULT_THEME').'/');
			defined('TPL_PATH') or define('TPL_PATH', ltrim(THEMES_PATH,'.'));
			tag('home_action');
			
			//$this->shieldingCountry();
			
			global $user,$language_id;
			if(session('user_id')){
				//if(S('user_info_'.session('user_id'))){
				//	$user = S('user_info_'.session('user_id'));
				//}else{
					$user = UserModel::get_user_info(session('user_id'));
					$user['sid'] = session_id();
					unset($user['password']);
					//S('user_info_'.session('user_id'), $user, array('expire'=>'3600'));
				//}
			}
			if(!isset($user) || empty($user)){
				$user = array();
				$user['sid'] = session_id();
			}

			//多语言
			if(!isset($language_id) || empty($language_id)){
				if(cookie('think_language_id')){
					$language_id = cookie('think_language_id');
					//自动选择货币
					if(! session('currency') || ! session('curr_change')){
						//西班牙 意大利语言 德语 特殊处理 当切换为西班牙 意大利语言 德语 语言时 显示欧元
						if(9 == cookie('think_language_id') || 10 == cookie('think_language_id') || 11 == cookie('think_language_id')){
							session('currency', 'EUR');
						}else{
							$currencyList = SiteModel::currency_list();
							foreach ($currencyList as $curr){
								if($curr['language_id'] == cookie('think_language_id')){
									session('currency', $curr['name']);
									break;
								}
							}
						}
					}
				}else{
					$language_id = C('language_id');
				}
			}


			//获取公共变量
			$this->assign($this->tags_style());
           
            //定义常用产品分类的URL
            $category_id_array = CategoryModel::get_category_id_array();
            $define_category_url =  S('define_category_url'); //获取分类路径缓存    
            if(!$define_category_url){
            	$define_category_url = array();
	            foreach($category_id_array as $cid){
	            	$category_url = CategoryModel::get_category_one_url($cid);
	            	$define_category_url['CATEGORY_URL_'.$cid] = $category_url;
					$category_newproduct_url = str_replace('category','new',$category_url);
					$define_category_url['NEWPRODUCT_URL_'.$cid] = $category_newproduct_url;
	            }
	            S('define_category_url', $define_category_url);
            }
            //定义
            foreach ($define_category_url as $name => $url) {
            	define($name,$url);
            }

            //统计购物车商品数量
            $cartProductList = CartModel::get_cart_product_list(); 
            $this->assign('headerCartCount',$cartProductList['total_number']);  
    }

    /**
     * 空操作
     */
    public function _empty()
    {
		// $where = array(
		// 	'is_sell' => 1,
		// 	'catid'=>2061,
		// );
		// $productList = ProductModel::get_product_list($where, 0, 20);
		// $this->assign('productList', $productList);
		send_http_status(404);
    	$this->display(C('ERROR_PAGE'));
    	exit;
    }
    
	/**
	 * 全站单个标签变量赋值,可在调用的类直接assign
	 */
    public function tags_style()
    {
    	C('TMPL_ACTION_ERROR', THEMES_PATH.'public/showmessage.phtml'); // 默认错误跳转对应的模板文件
			C('TMPL_ACTION_SUCCESS', THEMES_PATH.'public/showmessage.phtml'); // 默认成功跳转对应的模板文件
			C('ERROR_PAGE', THEMES_PATH.'public/404.phtml');
			
			$index_search = C('index_search');
			if(isset($index_search) && $index_search){
				$index_search = explode(',', $index_search);
			}

			$style = array();
			$style['site_name']  = C('site_name');
			$style['site_url']   = C('site_url');
			$style['site_email'] = C('site_email');
			$style['record'] = C('record');
			$style['copyright']= C('copyright');
			$style['domain_url'] = getHost();
			$style['currencyList'] = SiteModel::currency_list();
			$style['languageList'] = SiteModel::get_language_list();
			$style['index_search'] = $index_search;
			return $style;
    }	
   
	/**
	 * (non-PHPdoc)
	 * @see Action::error()
	 * @param $dialog dialog弹窗
	 */
	protected function error($message, $jumpUrl = '', $dialog = '', $ajax = false)
	{
		$this->assign('dialog', $dialog);
		parent::error($message, $jumpUrl, $ajax);
	}
	/**
	 * (non-PHPdoc)
	 * @see Action::success()
	 * @param $dialog dialog弹窗
	 */
	protected function success($message, $jumpUrl = '', $dialog = '', $ajax = false)
	{
		$this->assign('dialog', $dialog);
		parent::success($message, $jumpUrl, $ajax);
	}
	
	/**
	 * 单个附件上传
	 * @param string $subDir 子目录名称当$subType为custom时有效
	 * @param string $subType 子目录创建方式 可以使用hash date custom
	 * @param string $savePath 设置附件上传目录
	 * @param array $allowExts 设置附件上传类型
	 * @param boolean $thumb 设置是否开启缩略图
	 */
	final public static function upload($subDir = '', $subType = 'custom', $allowExts = array(),$thumb=false)
	{
		import('ORG.Net.UploadFile');
		$upload = new UploadFile();
		$upload->allowExts  = $allowExts ? $allowExts : array('jpg', 'gif', 'png', 'jpeg');
		$upload->savePath =  '.'.UPLOAD_PATH;
		$upload->autoSub = true;
		$upload->subType = $subType ? $subType : 'custom';
		$upload->subDir = $subDir.'/';
		$upload->thumb = $thumb;//开启缩略图
		$upload->thumbType = C('product_thumb_type') ? intval(C('product_thumb_type')) : 0;
		$upload->thumbMaxWidth = C('product_list_width').','.C('product_thumb_width').',250';
		$upload->thumbMaxHeight = C('product_list_height').','.C('product_thumb_height').',250';
		$upload->thumbPrefix = 'list_,thumb_,250x250_';
		if(!is_dir(UPLOAD_PATH . $subDir)){
			mkdir(UPLOAD_PATH . $subDir);
		}
		if(!$upload->upload()) {// 上传错误提示错误信息
			return $upload->getErrorMsg();
		}else{// 上传成功 获取上传文件信息
			$info = $upload->getUploadFileInfo();
				$fileArray = array();
				foreach ($info as $sinfo){
					$fileArray[$sinfo['key']] = $sinfo;
				}
				return $fileArray;
		}
	}
	
	/**
	 * 屏蔽国家访问
	 */
	private function shieldingCountry()
	{
		if(!isset($_SESSION['is_open_look']) ||(isset($_SESSION['is_open_look']) && $_SESSION['is_open_look'] != C('barred_access_password'))){
			//验证输入访问密码是否正确
			if(isset($_POST['access_pwd']) && $_POST['access_pwd']){
				if(C('barred_access_password') == trim($_POST['access_pwd'])){
					$_SESSION['is_open_look'] = C('barred_access_password');
					return true;
				}
			}
	
			$geo_code = cookie('geo_code');
			if(!$geo_code){
				$ip = get_client_ip();
		//		$ip = "113.64.139.176";//CN
				
		     //加载IP库
		      import('geoip', VENDOR_PATH."GeoIp", '.inc');
		      $gi = geoip_open(VENDOR_PATH."GeoIp/GeoIP.dat",GEOIP_STANDARD);
		      $geo_code = geoip_country_code_by_addr($gi, $ip);
		      cookie('geo_code', $geo_code);
			}
      //禁止访问国家
      $countryBarredList = C('barred_list') ? explode(',', C('barred_list')) : array();
	  
      if(in_array($geo_code, $countryBarredList) && $_SESSION['is_open_look'] != C('barred_access_password')){
	  	
		$wfbillno=fopen(ROOT_PATH."/web/Runtime/Logs/ip_deny-".date("Y-m-d").".log","a+");
		fwrite($wfbillno,date("Y-m-d H:i:s")."|Country[ ".$geo_code." ]IP[ ".get_client_ip()." ]"."\r\n");
		fclose($wfbillno);
		
      	$this->display('public/is_ip_check');exit;
      }
		}
	}

     //异步发送邮件
	public function sendMail()
	{
		$senddata = trim($_POST['senddata']);
		$senddata = json_decode(base64_decode($senddata),true);
		//Log::write('send_2 log:'.json_encode($senddata));
		if(is_array($senddata)){
		    $mailInstance = new EmailModel();
	  	    //取消订阅地址
  	        $unsubscribe_url = MeasureModel::unsubscribe_url($senddata['email']);
  		    $senddata['content'] = str_replace('{$unsubscribe_url}', $unsubscribe_url, $senddata['content']);		
		    $mailInstance->sendMail_direct($senddata['email'], $senddata['title'], $senddata['content'], $senddata['ishtml'], $senddata['username']);
		}
	}
}
?>